package com.tanger.common.jpa;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Description 分页参数构造器
 * @Author Hchenbin
 * @Date 2024-01-09 09:46
 * @Version 1.0
 */
@Data
@ApiModel(value = "分页请求参数")
public class PageParams extends QueryParams {

    @ApiModelProperty(value = "页码(必须大于0)", allowableValues = "1", required = true)
    private Integer page;
    @ApiModelProperty(value = "每页大小", allowableValues = "20",required = true)
    private Integer size;

    /**
     * 构造分页参数
     * @return
     */
    public Pageable getPageable() {
        List<Sort.Order> sortOrders = new ArrayList<>();
        if (Objects.isNull(page) || Objects.isNull(size)) {
          throw new IllegalArgumentException("参数错误");
        }
        if (!CollectionUtils.isEmpty(super.getSort())) {
            for (Order order : super.getSort()) {
                sortOrders.add(new Sort.Order(Sort.Direction.valueOf(order.getDirection()), order.getProperty()));
            }
            return PageRequest.of(page - 1, size, Sort.by(sortOrders));
        } else {
            return PageRequest.of(page - 1, size);
        }
    }

    public Integer getPage() {
        return page;
    }

    public PageParams setPage(Integer page) {
        this.page = page;
        return this;
    }

    public Integer getSize() {
        return size;
    }

    public PageParams setSize(Integer size) {
        this.size = size;
        return this;
    }
}
